package boundarys;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import controllers.MaintainingResidentialAreaController;
import controllers.UpdateClientController;
import entitys.Area;
import entitys.Customer;
import entitys.Reply;
import enums.Command;
import enums.Result;

public class UpdateClientGUI extends AbstractGUI{

	private JFrame frmUpdateClients;
	private JTextField FirstnameTextField;
	private JTextField LastnameTextField;
	private JTextField PhoneTextField;
	private JTextField EmailTextField;
	private JTextField IDTextField;
	JComboBox ListofCustComboBox;
	private JComboBox areascomboBox;
	private ArrayList<Area> areasList;
	private JLabel lblFirstName;
	private JLabel lblLastName;
	private JLabel lblBirth;
	private JLabel lblArea;
	private JLabel lblPhone;
	private JLabel lblEmail;
	private JLabel lblId;

	ArrayList<Customer> res;
	private JTextField BirthtextField;
	
	/**
	 * Update client GUI constructor. 
	 * This method initializes the window,buttons, labels etc...
	 */
	public UpdateClientGUI() {
		initialize();
		initGUI(frmUpdateClients);
	}

	/**
	 * Initialize the contents of the frame.
	 * Set up each components size, location etc...
	 */
	private void initialize() {
		frmUpdateClients = new JFrame();
		frmUpdateClients.setTitle("... Manage Clients > Update Client");
		frmUpdateClients.setBounds(100, 100, 435, 370);
		frmUpdateClients.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmUpdateClients.getContentPane().setLayout(null);
		
		FirstnameTextField = new JTextField();
		FirstnameTextField.setBounds(108, 81, 192, 20);
		frmUpdateClients.getContentPane().add(FirstnameTextField);
		FirstnameTextField.setColumns(10);
		
		LastnameTextField = new JTextField();
		LastnameTextField.setBounds(108, 112, 192, 20);
		frmUpdateClients.getContentPane().add(LastnameTextField);
		LastnameTextField.setColumns(10);
		
		PhoneTextField = new JTextField();
		PhoneTextField.setBounds(108, 143, 192, 20);
		frmUpdateClients.getContentPane().add(PhoneTextField);
		PhoneTextField.setColumns(10);
		
		EmailTextField = new JTextField();
		EmailTextField.setBounds(108, 171, 192, 20);
		frmUpdateClients.getContentPane().add(EmailTextField);
		EmailTextField.setColumns(10);
		
		IDTextField = new JTextField();
		IDTextField.setBounds(108, 50, 192, 20);
		frmUpdateClients.getContentPane().add(IDTextField);
		IDTextField.setColumns(10);
		IDTextField.disable();
		
	    lblFirstName = new JLabel("First Name :");
		lblFirstName.setBounds(29, 84, 94, 14);
		frmUpdateClients.getContentPane().add(lblFirstName);

		lblLastName = new JLabel("Last Name :");
		lblLastName.setBounds(29, 115, 94, 14);
		frmUpdateClients.getContentPane().add(lblLastName);
		
		lblArea = new JLabel("Area :");
		lblArea.setBounds(29, 208, 94, 14);
		frmUpdateClients.getContentPane().add(lblArea);
		
		lblPhone = new JLabel("Phone :");
		lblPhone.setBounds(29, 146, 94, 14);
		frmUpdateClients.getContentPane().add(lblPhone);
		
		lblEmail = new JLabel("Email :");
		lblEmail.setBounds(29, 177, 94, 14);
		frmUpdateClients.getContentPane().add(lblEmail);
		
		lblId = new JLabel("ID :");
		lblId.setBounds(29, 53, 46, 14);
		frmUpdateClients.getContentPane().add(lblId);
		
		JCheckBox chckbxAllow = new JCheckBox("Allow future addressing");
		chckbxAllow.setBounds(108, 268, 152, 23);
		frmUpdateClients.getContentPane().add(chckbxAllow);
		
		JButton btnConfirm = new JButton("Confirm");
		btnConfirm.addActionListener(new ActionListener() {
			/**
			 * Listener for the confirm button.
			 * When a click is occurred, check the following inputs.
			 * > First name not null.
			 * > Address not null.
			 * > ID not null and valid.
			 * > Phone is valid.
			 * > Birthdate is valid.
			 * 
			 * If everything is good, call controller function.
			 */
			public void actionPerformed(ActionEvent e) {
				boolean ok = true;
				if(FirstnameTextField.getText().trim().equals("") || ValidateFirstOrLastName(FirstnameTextField.getText())==0)
				{
					lblFirstName.setForeground(Color.RED);
					ok = false;
				}
				else
					lblFirstName.setForeground(Color.BLACK);
				if(!LastnameTextField.getText().trim().isEmpty() && ValidateFirstOrLastName(LastnameTextField.getText())==0)
				{
					lblLastName.setForeground(Color.RED);
					ok = false;
				}
				else
					lblLastName.setForeground(Color.BLACK);
				if(EmailTextField.getText().trim().equals("") || (EmailTextField.getForeground()==Color.GRAY && !EmailTextField.getText().isEmpty()) || ValidateEmail(EmailTextField.getText())==0)
				{
					lblEmail.setForeground(Color.RED);
					ok = false;
				}
				else
					lblEmail.setForeground(Color.BLACK);
				if(ValidateIDorPhone(PhoneTextField.getText())==0)
				{
					lblPhone.setForeground(Color.RED);
					ok = false;
				}
				else
					lblPhone.setForeground(Color.BLACK);
				if(ValidateBirth(BirthtextField.getText())==0)
				{
					lblBirth.setForeground(Color.RED);
					ok = false;
				}
				else
					lblBirth.setForeground(Color.BLACK);
				
					if(ok)
					UpdateClientController.updateClient(IDTextField.getText(),FirstnameTextField.getText(),LastnameTextField.getText(),EmailTextField.getText(),PhoneTextField.getText(),(String)areascomboBox.getSelectedItem(),chckbxAllow.isSelected(),BirthtextField.getText());
		}});
		btnConfirm.setBounds(211, 298, 89, 23);
		frmUpdateClients.getContentPane().add(btnConfirm);
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frmUpdateClients.dispose();
				goBack();
			}
		});
		btnCancel.setBounds(29, 298, 89, 23);
		frmUpdateClients.getContentPane().add(btnCancel);
		
		ListofCustComboBox = new JComboBox();
		ListofCustComboBox.addActionListener(new ActionListener() {
			/**
			 * Listener for the combo box of clients.
			 * When a click is occurred update the text fields according to the customer chosen.
			 */
			public void actionPerformed(ActionEvent arg0) {
				Customer c = (Customer) ListofCustComboBox.getSelectedItem();
				IDTextField.setText(c.getId());
				FirstnameTextField.setText(c.getFirstName());
				LastnameTextField.setText(c.getLastName());
				PhoneTextField.setText(c.getPhone());
				EmailTextField.setText(c.getEmail());
				areascomboBox.setSelectedItem((c.getAddress()));
				chckbxAllow.setSelected(c.getPermit());
				BirthtextField.setText(c.getBirthdate());
			}
		});
		ListofCustComboBox.setBounds(29, 19, 271, 20);
		frmUpdateClients.getContentPane().add(ListofCustComboBox);
		
		UpdateClientController.getClients();
		
		JLabel lblChooseCustomer = new JLabel("");
		lblChooseCustomer.setBounds(29, 28, 106, 14);
		frmUpdateClients.getContentPane().add(lblChooseCustomer);
		
		BirthtextField = new JTextField();
		BirthtextField.setBounds(108, 233, 192, 20);
		frmUpdateClients.getContentPane().add(BirthtextField);
		BirthtextField.setColumns(10);
		
		lblBirth = new JLabel("Birthdate :");
		lblBirth.setBounds(29, 236, 69, 14);
		frmUpdateClients.getContentPane().add(lblBirth);
		
		areascomboBox = new JComboBox();
		areascomboBox.setBounds(108, 202, 192, 20);
		frmUpdateClients.getContentPane().add(areascomboBox);
		
		JButton RefreshButton = new JButton("Refresh");
		RefreshButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				UpdateClientController.getClients();
				MaintainingResidentialAreaController.getAreas();
			}
		});
		RefreshButton.setBounds(330, 19, 79, 20);
		frmUpdateClients.getContentPane().add(RefreshButton);
		MaintainingResidentialAreaController.getAreas();
		frmUpdateClients.setVisible(true);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * AbstractGUI overridden method for getting a reply from server 
	 */
	public void getReply(Object r) {
		if(((Reply)r).command.equals(Command.GET_CLIENTS))
		{
			ListofCustComboBox.removeAll();
			res=(ArrayList<Customer>) ((Reply)r).result;
			for(int i=0;i<res.size();i++)
			{
				ListofCustComboBox.addItem(res.get(i));
			}
		}
		else if(((Reply)r).command.equals(Command.UPDATE_CLIENT))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Client updated successfully!");
				JOptionPane.showMessageDialog(frmUpdateClients, "Client updated successfully", "CCRM Update Client", JOptionPane.INFORMATION_MESSAGE);
				goBack();
			}
			System.out.println(((Reply)r).result);
			
		}
		
		else if(((Reply)r).command.equals(Command.GET_AREAS))
		{
			String tmp;
			areasList=(ArrayList<Area>) ((Reply)r).result;
			areascomboBox.removeAllItems();
			for(int i=0;i<areasList.size();i++)
			{
				tmp = areasList.get(i).getAreaName();
				areascomboBox.addItem(tmp);
			}
		}

	}
	
	/**
	 * Method for checking if ID or phone is valid.
	 * Both must be not null and contain only numbers.
	 */
	public int ValidateIDorPhone(String id)
	{
		int i;
		if(id.length()==0)
			return 0;
		for (i=0;i<id.length();i++)
			if(id.charAt(i)>'9' || id.charAt(i)<'0')
				return 0;
		return 1;
	}
	/**
	 * Method for checking if birthdate is valid.
	 * It must be not null and in the form of YYYY-MM-DD, and contain only numbers.
	 */
	public int ValidateBirth(String birth)
	{
		int i,year,month,day;
		if(birth.length()!=10)
			return 0;
		if(birth.charAt(4)!='-' || birth.charAt(7)!='-')
			return 0;
		for (i=0;i<birth.length();i++)
			if(i!=4 && i!=7)
				if(birth.charAt(i)>'9' || birth.charAt(i)<'0')
					return 0;
		year = Integer.parseInt(birth.substring(0, 4));
		month = Integer.parseInt(birth.substring(5, 7));
		day = Integer.parseInt(birth.substring(8, 10));
		if(year<=0 || month>12 || month<=0 || day>31 || day<=0)
			return 0;
		return 1;
	}
	/**
	 * Method for checking if first or last name is valid.
	 * It must contain only letters a-z or A-Z.
	 */
	public int ValidateFirstOrLastName(String text)
	{
		for(int i=0;i<text.length();i++)
		{
			if(!((text.charAt(i)>='a' && text.charAt(i)<='z') || (text.charAt(i)>='A' && text.charAt(i)<='Z') || text.charAt(i)==' '))
				return 0;
		}
		return 1;
	}
	
	/**
	 * Method for checking if email is valid.
	 * It must be not null and in the form of abc@abc.com.
	 */
	public int ValidateEmail(String email)
	{
		String tmp;
		int i=0;
		int length=email.length();
		
		if(!email.endsWith(".com")) return 0;
		while(i<email.length() && email.charAt(i)!='@')
		{
			if(!validChar(email.charAt(i))) return 0;
			i++;
		}
		if(i==0) return 0;
		i++;
		while(i<email.length() && email.charAt(i)!='.')
		{
			if(!validChar(email.charAt(i))) return 0;
			i++;
		}
		if(!validChar(email.charAt(i+1))) return 0;
		if(i==email.length()-1) return 0;
		else return 1;
	}
	/**
	 * Helping method for checking if email is valid.
	 * Validating each char.
	 */
	public boolean validChar(char c)
	{
		return ((c>='0' && c<='9') || (c>='a' && c<='z') || (c>='A' && c<='Z') || c==' ');
	}
}
